package model

import (
	"gin-project/utils"
	"gin-project/utils/errmsg"
	"gorm.io/gorm"
	"mime/multipart"
	"strconv"
)

type Song struct {
	gorm.Model
	SingerID     int    `json:"singer_id"`
	Name         string `json:"name"`
	Introduction string `json:"introduction"`
	Pic          string `json:"pic"`
	Lyric        string `json:"lyric"`
	Url          string `json:"url"`
}

func (Song) TableName() string {
	return "song"
}

// 根据歌手id查询歌曲
func SelectSongsBySingerID(id string) (*Singer, int) {
	convID, _ := strconv.Atoi(id)
	var singer Singer
	err := db.Preload("Songs").Where("id = ?", convID).Find(&singer).Error
	if err != nil {
		return nil, errmsg.SONG_SELECT_FAILED
	}
	return &singer, errmsg.SUCCESS
}

// 更新歌手图片
func UploadSongUrl(file multipart.File, header *multipart.FileHeader) (string, int) {
	url, code := utils.UploadFile(file, header.Size)
	return url, code
}

// 增加歌曲
func InsertSong(song *Song) int {
	err := db.Create(&song).Error
	if err != nil {
		return errmsg.SINGER_DELETE_FAILED
	}
	return errmsg.SUCCESS
}

// 更新歌曲
func UpdateSong(m map[string]interface{}, id string) int {
	convID, _ := strconv.Atoi(id)
	err := db.Model(&Song{}).Where("id = ?", convID).Updates(m).Error
	if err != nil {
		return errmsg.SONG_UPDATE_FAILED
	}
	return errmsg.SUCCESS
}

// 更新歌曲图片
func UpdateSongPic(file multipart.File, header *multipart.FileHeader) (string, int) {
	url, code := utils.UploadFile(file, header.Size)
	return url, code
}

// 更新歌曲URL
func UpdateSongUrl(file multipart.File, header *multipart.FileHeader) (string, int) {
	url, code := utils.UploadFile(file, header.Size)
	return url, code
}

// 根据id删除歌曲
func DeleteSong(id string) int {
	convID, _ := strconv.Atoi(id)
	err := db.Where("id = ?", convID).Delete(&Song{}).Error
	if err != nil {
		return errmsg.SONG_DELETE_FAILED
	}
	return errmsg.SUCCESS
}

// 根据歌曲名查询歌曲
func SelectSongByName(name string) (*Song, int) {
	var song Song
	err := db.Where("name = ?", name).Find(&song).Error
	if err != nil {
		return nil, errmsg.SONG_SELECT_FAILED
	}
	return &song, errmsg.SUCCESS
}

// 根据id查询歌曲
func SelectSongByID(id string) (Song, int) {
	convID, _ := strconv.Atoi(id)
	var song Song
	err := db.Where("id = ?", convID).Find(&song).Error
	if err != nil {
		return Song{}, errmsg.SONG_SELECT_FAILED
	}
	return song, errmsg.SUCCESS
}

// 查询所有的歌曲
func SelectSongAll() ([]*Song, int) {
	var songs []*Song
	err := db.Find(&songs).Error
	if err != nil {
		return nil, errmsg.SONG_SELECT_FAILED
	}
	return songs, errmsg.SUCCESS
}

// 根据歌曲名字模糊搜索
func SelectLikeName(name string) ([]*Song, int) {
	var songs []*Song
	err := db.Debug().Where("name like ?", "%"+name+"%").Find(&songs).Error
	if err != nil {
		return nil, errmsg.SONG_SELECT_FAILED
	}
	return songs, errmsg.SUCCESS
}
